package com.example.fill;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.util.AttributeSet;
import android.view.SurfaceHolder;
import android.view.SurfaceView;

import androidx.annotation.NonNull;

public class TestMove extends SurfaceView implements SurfaceHolder.Callback, Runnable {

    private SurfaceHolder holder;

    private Canvas canvas;

    private boolean isDrawing = false;

    private Thread thread;

     Person person;

    public TestMove(Context context) {
        super(context);
        init();
    }

    public TestMove(Context context, AttributeSet attrs) {
        super(context, attrs);
        init();
    }

    public TestMove(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init();
    }

    public TestMove(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
        super(context, attrs, defStyleAttr, defStyleRes);
    }

    private void init() {
        person = new Person(getContext());
        holder = getHolder();
        holder.addCallback(this);
    }

    @Override
    public void surfaceCreated(@NonNull SurfaceHolder holder) {
        isDrawing = true;
        thread = new Thread(this);
        thread.start();
    }

    @Override
    public void surfaceChanged(@NonNull SurfaceHolder holder, int format, int width, int height) {

    }

    @Override
    public void surfaceDestroyed(@NonNull SurfaceHolder holder) {
        while (thread.isAlive()){
            isDrawing = false;
        }
    }

    @Override
    public void run() {
        while (isDrawing) {
            startDraw();
        }
    }

    private void startDraw(){
        canvas = holder.lockCanvas();
        if (canvas != null){
            canvas.drawColor(Color.WHITE);
            canvas.drawBitmap(person.now,person.local.x,person.local.y,null);

            holder.unlockCanvasAndPost(canvas);
        }
    }
}
